package com.opencee.cloud.bpm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.opencee.boot.db.mybatis.service.impl.SupperServiceImpl;
import com.opencee.cloud.bpm.entity.BpmCategoryEntity;
import com.opencee.cloud.bpm.entity.BpmFormEntity;
import com.opencee.cloud.bpm.mapper.BpmFormProcessMapper;
import com.opencee.cloud.bpm.service.IBpmCategoryService;
import com.opencee.cloud.bpm.service.IBpmFormService;
import com.opencee.cloud.bpm.vo.BpmCategoryListVO;
import com.opencee.cloud.bpm.vo.BpmFormListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 流程表单信息 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-01-02
 */
@Service
public class BpmFormServiceImpl extends SupperServiceImpl<BpmFormProcessMapper, BpmFormEntity> implements IBpmFormService {

    @Autowired
    private IBpmCategoryService bpmCategoryService;

    /**
     * 根据流程key获取表单信息
     *
     * @param processKey
     * @return
     */
    @Override
    public BpmFormEntity getByProcessKey(String processKey) {
        QueryWrapper<BpmFormEntity> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(BpmFormEntity::getProcessKey, processKey);
        return this.getOne(queryWrapper);
    }

    /**
     * 查询分类表单列表
     *
     * @return
     */
    @Override
    public List<BpmCategoryListVO> listCategoryForm() {
        QueryWrapper<BpmCategoryEntity> categoryQuery = new QueryWrapper<>();
        categoryQuery.lambda().eq(BpmCategoryEntity::getStatus, 1)
                .orderByDesc(BpmCategoryEntity::getStatus);
        List<BpmCategoryEntity> categoryList = bpmCategoryService.list(categoryQuery);
        List<BpmFormListVO> formList = this.baseMapper.selectBpmFormListVO();
        Map<Long, List<BpmFormListVO>> formMap = formList.stream().collect(Collectors.groupingBy(BpmFormListVO::getCategoryId));
        List<BpmCategoryListVO> list = categoryList.stream().map(t -> {
            List<BpmFormListVO> formListVOS = formMap.getOrDefault(t.getId(), Collections.emptyList());
            BpmCategoryListVO vo = new BpmCategoryListVO();
            vo.setCategoryId(t.getId());
            vo.setCategoryName(t.getName());
            vo.setFormList(formListVOS);
            vo.setCount(formListVOS.size());
            return vo;
        }).collect(Collectors.toList());
        return list;
    }
}
